<template>
	<div class="login-container">
		<div class="login-header">
			<h1 class="logo-text">拓 信IM</h1>
		</div>
		
		<div class="login-box" v-loading="isload" element-loading-text="拼命加载中...">
			<div class="login-card" :class="{'flip': isFlipped}">
				<!-- 登录面板 -->
				<div class="card-face card-front">
					<div class="card-content">
						<h2 class="title">欢迎回来</h2>
						
						<el-tabs v-model="loginType" class="login-tabs">
							<el-tab-pane label="账号登录" name="account">
								<el-form 
									class="login-form" 
									:model="loginForm" 
									:rules="rules" 
									ref="loginForm" 
									@keyup.enter="submitForm('loginForm')">
									
									<el-form-item prop="mobile">
										<el-input 
											v-model="loginForm.mobile" 
											placeholder="请输入用户名"
											:prefix-icon="User"
											class="login-input">
										</el-input>
									</el-form-item>
									
									<el-form-item prop="password">
										<el-input 
											type="password" 
											v-model="loginForm.password" 
											placeholder="请输入密码"
											:prefix-icon="Lock"
											show-password
											class="login-input">
										</el-input>
									</el-form-item>
									
									<div class="forgot-password">
										<span @click="showForgotDialog">忘记密码？</span>
									</div>
									
									<el-button type="primary" class="login-button" @click="submitForm('loginForm')" round>登 录</el-button>
								</el-form>
							</el-tab-pane>
							
							<el-tab-pane label="扫码登录" name="qrcode">
								<div class="qrcode-container">
									<div class="qrcode-wrapper" :class="{ 'expired': isQrcodeExpired }">
										<img v-if="!qrcodeUrl" src="@/assets/image/demo-qrcode.png" alt="登录二维码" class="qrcode-img"/>
										<img v-else :src="qrcodeUrl" alt="登录二维码" class="qrcode-img"/>
										<div class="qrcode-mask" v-if="isQrcodeExpired">
											<p>二维码已失效</p>
											<el-button type="primary" @click="refreshQrcode" round>刷新二维码</el-button>
										</div>
									</div>
									<div class="qrcode-tip">
										<p class="scan-tip">使用拓信APP扫码登录</p>
										<el-countdown 
											v-if="!isQrcodeExpired" 
											:value="countdownTime"
											format="ss秒后失效"
											@finish="handleCountdownFinish"
											class="countdown"
										/>
									</div>
								</div>
							</el-tab-pane>
						</el-tabs>
						
						<div class="register-link">
							<span class="register-text">还没有账号？</span>
							<el-button link @click="flipCard" class="flip-button">立即注册</el-button>
						</div>
						
						<el-form-item prop="terminal" style="display: none;">
							<el-input type="hidden" v-model="loginForm.terminal"></el-input>
						</el-form-item>
					</div>
				</div>
				
				<!-- 注册面板 -->
				<div class="card-face card-back">
					<div class="card-content">
						<h2 class="title">创建账号</h2>
						<div class="register-form">
							<el-input 
								placeholder="请输入手机号码" 
								:prefix-icon="Phone"
								class="login-input">
							</el-input>
							
							<el-input 
								type="password" 
								placeholder="请设置密码" 
								:prefix-icon="Lock"
								show-password
								class="login-input">
							</el-input>
							
							<el-input 
								type="password" 
								placeholder="请确认密码" 
								:prefix-icon="Lock"
								show-password
								class="login-input">
							</el-input>
							
							<el-button type="primary" class="login-button" @click="register('registerForm')" round>注 册</el-button>
							
							<div class="login-link">
								已有账号？<el-button link @click="flipCard" class="flip-button">返回登录</el-button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<div class="icp-container">
			<Icp />
		</div>
		
		<!-- 添加忘记密码对话框 -->
		<el-dialog
			v-model="forgotDialogVisible"
			title="找回密码"
			width="400px"
			:close-on-click-modal="false"
			class="forgot-dialog"
		>
			<el-form ref="forgotForm" :model="forgotForm" :rules="forgotRules" label-width="0">
				<el-form-item>
					<el-radio-group v-model="forgotForm.verifyType">
						<el-radio label="mobile">手机号验证</el-radio>
						<el-radio label="email">邮箱验证</el-radio>
					</el-radio-group>
				</el-form-item>
				
				<el-form-item prop="account">
					<el-input
						v-model="forgotForm.account"
						:placeholder="forgotForm.verifyType === 'mobile' ? '请输入手机号' : '请输入邮箱'"
						:prefix-icon="forgotForm.verifyType === 'mobile' ? Phone : Message"
					></el-input>
				</el-form-item>
				
				<el-form-item prop="verifyCode" class="verify-code-item">
					<el-input
						v-model="forgotForm.verifyCode"
						placeholder="请输入验证码"
						:prefix-icon="Key"
					>
						<template #append>
							<el-button 
								:disabled="isCountingDown" 
								@click="sendVerifyCode"
							>
								{{ countDownText }}
							</el-button>
						</template>
					</el-input>
				</el-form-item>
				
				<el-form-item prop="newPassword">
					<el-input
						v-model="forgotForm.newPassword"
						type="password"
						placeholder="请输入新密码"
						:prefix-icon="Lock"
						show-password
					></el-input>
				</el-form-item>
				
				<el-form-item prop="confirmPassword">
					<el-input
						v-model="forgotForm.confirmPassword"
						type="password"
						placeholder="请确认新密码"
						:prefix-icon="Lock"
						show-password
					></el-input>
				</el-form-item>
			</el-form>
			
			<template #footer>
				<el-button @click="forgotDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForgotForm">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script>
import { User, Lock, Phone, Message, Key } from '@element-plus/icons-vue'
import { markRaw } from 'vue'
import { setToken } from '@/utils/auth'
import Icp from '../components/common/Icp.vue'

export default {
	name: "login",
	components: {
		Icp
	},
	data() {
		// 验证手机号格式
		const validateMobile = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入手机号'));
			} else if (!/^1[3-9]\d{9}$/.test(value)) {
				callback(new Error('请输入正确的手机号'));
			} else {
				callback();
			}
		};
		
		// 验证邮箱格式
		const validateEmail = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入邮箱'));
			} else if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
				callback(new Error('请输入正确的邮箱'));
			} else {
				callback();
			}
		};
		
		// 验证账号格式（根据验证类型动态验证）
		const validateAccount = (rule, value, callback) => {
			if (this.forgotForm.verifyType === 'mobile') {
				validateMobile(rule, value, callback);
			} else {
				validateEmail(rule, value, callback);
			}
		};
		
		// 验证确认密码
		const validateConfirmPassword = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.forgotForm.newPassword) {
				callback(new Error('两次输入的密码不一致'));
			} else {
				callback();
			}
		};

		var checkUsername = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('请输入用户名'));
			}
			callback();
		};
		var checkPassword = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'));
			}
			callback();
		};
		return {
			isFlipped: false,
			isload: false,
			loginType: 'account',
			loginForm: {
				terminal: this.$enums.TERMINAL_TYPE.WEB,
				mobile: '',
				password: ''
			},
			rules: {
				mobile: [{
					validator: checkUsername,
					trigger: 'blur'
				}],
				password: [{
					validator: checkPassword,
					trigger: 'blur'
				}]
			},
			User: markRaw(User),
			Lock: markRaw(Lock),
			Phone: markRaw(Phone),
			Message: markRaw(Message),
			Key: markRaw(Key),
			// 二维码相关数据
			qrcodeUrl: '',
			qrcodeId: '',
			isQrcodeExpired: false,
			countdownTime: Date.now() + 20 * 1000, // 20秒的倒计时
			checkLoginTimer: null,
			// 忘记密码相关数据
			forgotDialogVisible: false,
			forgotForm: {
				verifyType: 'mobile',
				account: '',
				verifyCode: '',
				newPassword: '',
				confirmPassword: ''
			},
			forgotRules: {
				account: [{ validator: validateAccount, trigger: 'blur' }],
				verifyCode: [
					{ required: true, message: '请输入验证码', trigger: 'blur' },
					{ min: 6, max: 6, message: '验证码长度应为6位', trigger: 'blur' }
				],
				newPassword: [
					{ required: true, message: '请输入新密码', trigger: 'blur' },
					{ min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
				],
				confirmPassword: [{ validator: validateConfirmPassword, trigger: 'blur' }]
			},
			countDown: 0
		};
	},
	created(){
		this.setCookie('mobile', '18468015201');
		this.setCookie('password', '123123');
	},
	watch: {
		loginType(newVal) {
			if (newVal === 'qrcode') {
				this.generateQrcode();
			} else {
				this.clearQrcodeTimer();
			}
		},
		'forgotForm.verifyType'() {
			this.forgotForm.account = '';
			this.forgotForm.verifyCode = '';
			this.$refs.forgotForm?.clearValidate('account');
		}
	},
	beforeDestroy() {
		this.clearQrcodeTimer();
	},
	beforeUnmount() {
		this.clearQrcodeTimer();
	},
	methods: {
		flipCard() {
			this.isFlipped = !this.isFlipped;
		},
		register(msg) {
			this.$message({
				message: "暂不能提供注册功能！我们正在努力开发中...",
				type: "warning",
				duration: 3000
			});
		},
		submitForm(formName) {
			this.isload = true;
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.$http({
						url: "/win/login",
						method: 'post',
						data: this.loginForm
					})
					.then((data) => {             
						if(data){
							// 保存密码到cookie(不安全)
							this.setCookie('mobile', this.loginForm.mobile);
							this.setCookie('password', this.loginForm.password);
							setToken(data)
							sessionStorage.setItem('accessToken',data.accessToken);
							this.$message({
								message: "登录成功",
								type: "success",
								duration: 2000
							});
							// 修改跳转路径
							this.$router.replace('/home/chat');
						}
					})
					.catch(error => {
						console.error('登录错误:', error);
						this.$message({
							message: error.message || "登录失败，请重试",
							type: "error",
							duration: 3000
						});
					})
					.finally(() => {
						this.isload = false;
					});
				} else {
					this.isload = false;
				}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		// 获取cookie
		getCookie(name) {
			let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
			let arr = document.cookie.match(reg)
			if (arr) {
				return unescape(arr[2]);
			}
			return '';
		},
		// 设置cookie
		setCookie(name, value, expiredays) {
			var exdate = new Date();
			exdate.setDate(exdate.getDate() + expiredays);
			document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
		},
		// 删除cookie
		delCookie(name) {
			var exp = new Date();
			exp.setTime(exp.getTime() - 1);
			var cval = this.getCookie(name);
			if (cval != null) {
				document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
			}
		},
		async generateQrcode() {
			try {
				this.isload = true;
				const response = await this.$http({
					url: "/win/qrcode/generate",
					method: 'get'
				});
				
				if (response && response.data) {
					this.qrcodeUrl = response.data.qrcodeUrl;
					this.qrcodeId = response.data.qrcodeId;
					this.isQrcodeExpired = false;
					this.countdownTime = Date.now() + 20 * 1000; // 重置倒计时
					this.startCheckLogin();
				}
			} catch (error) {
				this.$message.error('生成二维码失败，请重试');
			} finally {
				this.isload = false;
			}
		},
		
		handleCountdownFinish() {
			this.isQrcodeExpired = true;
			this.clearQrcodeTimer();
		},
		
		refreshQrcode() {
			this.clearQrcodeTimer();
			this.generateQrcode();
		},
		
		startCheckLogin() {
			this.checkLoginTimer = window.setInterval(async () => {
				if (!this.isQrcodeExpired && this.qrcodeId) {
					try {
						const response = await this.$http({
							url: `/win/qrcode/check/${this.qrcodeId}`,
							method: 'get'
						});
						
						if (response.data.status === 'CONFIRMED') {
							this.clearQrcodeTimer();
							setToken(response.data.token);
							sessionStorage.setItem('accessToken', response.data.token);
							this.$message.success('登录成功');
							this.$router.replace('/home/chat');
						}
					} catch (error) {
						console.error('检查登录状态失败:', error);
					}
				}
			}, 2000);
		},
		
		clearQrcodeTimer() {
			if (this.checkLoginTimer) {
				clearInterval(this.checkLoginTimer);
				this.checkLoginTimer = null;
			}
		},
		// 显示忘记密码对话框
		showForgotDialog() {
			this.forgotDialogVisible = true;
			this.forgotForm = {
				verifyType: 'mobile',
				account: '',
				verifyCode: '',
				newPassword: '',
				confirmPassword: ''
			};
			this.countDown = 0;
		},
		
		// 发送验证码
		async sendVerifyCode() {
			try {
				// 先验证账号格式
				await this.$refs.forgotForm.validateField('account');
				
				// 发送验证码请求
				await this.$http({
					url: '/win/verify/send',
					method: 'post',
					data: {
						type: this.forgotForm.verifyType,
						account: this.forgotForm.account
					}
				});
				
				// 开始倒计时
				this.countDown = 60;
				const timer = setInterval(() => {
					if (this.countDown > 0) {
						this.countDown--;
					} else {
						clearInterval(timer);
					}
				}, 1000);
				
				this.$message.success('验证码已发送');
			} catch (error) {
				if (error.message) {
					this.$message.error(error.message);
				}
			}
		},
		
		// 提交忘记密码表单
		async submitForgotForm() {
			try {
				await this.$refs.forgotForm.validate();
				
				await this.$http({
					url: '/win/password/reset',
					method: 'post',
					data: this.forgotForm
				});
				
				this.$message.success('密码重置成功');
				this.forgotDialogVisible = false;
			} catch (error) {
				if (error.message) {
					this.$message.error(error.message);
				}
			}
		}
	},
	computed: {
		isCountingDown() {
			return this.countDown > 0;
		},
		countDownText() {
			return this.isCountingDown ? `${this.countDown}秒后重试` : '发送验证码';
		}
	},
	mounted() {
		this.loginForm.mobile = this.getCookie("mobile");
		this.loginForm.password = this.getCookie("password");
		if (this.loginType === 'qrcode') {
			this.generateQrcode();
		}
	}
}
</script>

<style>
.login-container {
	position: fixed;
	top: 0;
	left: 0;
	width: 100vw;
	height: 100vh;
	background-image: url('../assets/image/login.jpg');
	background-size: cover;
	background-position: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.login-header {
	margin-bottom: 30px;
	text-align: center;
}

.logo-text {
	font-size: 36px;
	font-weight: bold;
	color: #333;
	text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-box {
	width: 100%;
	max-width: 400px;
	perspective: 1000px;
}

.login-card {
	width: 100%;
	position: relative;
	height: 480px;
	transition: transform 0.8s;
	transform-style: preserve-3d;
}

.login-card.flip {
	transform: rotateY(180deg);
}

.card-face {
	position: absolute;
	width: 100%;
	height: 100%;
	backface-visibility: hidden;
	border-radius: 16px;
	overflow: hidden;
	background: rgba(255, 255, 255, 0.4);
	backdrop-filter: blur(10px);
	box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.card-front {
	transform: rotateY(0);
}

.card-back {
	transform: rotateY(180deg);
}

.card-content {
	padding: 30px;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.title {
	font-size: 28px;
	color: #333;
	text-align: center;
	margin-bottom: 30px;
	font-weight: 600;
}

.login-form, .register-form {
	width: 100%;
}

.login-input {
	margin-bottom: 20px;
}

.login-input :deep(.el-input__wrapper) {
	padding: 1px 15px;
	height: 48px;
	border-radius: 8px;
	box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2);
	background-color: rgba(255, 255, 255, 0.3);
	backdrop-filter: blur(5px);
	transition: all 0.3s ease;
}

.login-input :deep(.el-input__wrapper):hover {
	box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.5);
	background-color: rgba(255, 255, 255, 0.4);
}

.login-input :deep(.el-input__wrapper.is-focus) {
	box-shadow: 0 0 0 1px #409EFF, 0 4px 12px rgba(64, 158, 255, 0.2);
	background-color: rgba(255, 255, 255, 0.5);
}

.login-input :deep(.el-input__inner) {
	height: 48px;
	font-size: 16px;
}

.login-button {
	width: 100%;
	height: 48px;
	margin-top: 15px;
	font-size: 16px;
	letter-spacing: 2px;
	background: linear-gradient(90deg, #409EFF, #36D1DC);
	border: none;
	transition: all 0.3s ease;
}

.login-button:hover {
	transform: translateY(-2px);
	box-shadow: 0 5px 15px rgba(54, 209, 220, 0.3);
	background: linear-gradient(90deg, #36D1DC, #409EFF);
}

.forgot-password {
	text-align: right;
	margin-bottom: 20px;
	font-size: 14px;
	color: #666;
	cursor: pointer;
}

.forgot-password span:hover {
	color: #409EFF;
}

.register-link, .login-link {
	margin-top: 20px;
	text-align: center;
	font-size: 14px;
	color: #666;
}

.flip-button {
	font-size: 14px;
	font-weight: 500;
	padding: 0 4px;
}

.flip-button:hover {
	text-decoration: underline;
}

.icp-container {
	position: fixed;
	bottom: 20px;
	width: 100%;
	text-align: center;
	color: rgba(255, 255, 255, 0.8);
	font-size: 12px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
	.login-box {
		max-width: 85%;
	}
}

.login-tabs {
	margin-bottom: 20px;
}

.login-tabs :deep(.el-tabs__item) {
	font-size: 16px;
	color: #666;
	font-weight: 500;
}

.login-tabs :deep(.el-tabs__item.is-active) {
	color: #409EFF;
	font-weight: 600;
}

.qrcode-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 30px 0;
}

.qrcode-wrapper {
	position: relative;
	width: 220px;
	height: 220px;
	margin-bottom: 20px;
	padding: 10px;
	border: 1px solid #eaeaea;
	border-radius: 12px;
	background: #fff;
}

.qrcode-img {
	width: 100%;
	height: 100%;
	object-fit: contain;
}

.qrcode-mask {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(255, 255, 255, 0.95);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	gap: 15px;
	border-radius: 12px;
}

.qrcode-mask p {
	font-size: 16px;
	color: #333;
	font-weight: 500;
}

.qrcode-tip {
	text-align: center;
}

.scan-tip {
	font-size: 16px;
	color: #333;
	font-weight: 500;
	margin-bottom: 8px;
}

.countdown {
	color: #409EFF;
	font-size: 14px;
	font-weight: 500;
	--el-countdown-content-font-size: 14px;
}

.register-link {
	margin-top: 20px;
	text-align: center;
}

.register-text {
	font-size: 14px;
	color: #333;
}

.expired .qrcode-img {
	filter: grayscale(100%);
	opacity: 0.6;
}

/* 添加忘记密码对话框样式 */
.forgot-dialog {
	.verify-code-item {
		:deep(.el-input-group__append) {
			padding: 0;
			
			.el-button {
				border: none;
				height: 100%;
				padding: 0 15px;
			}
		}
	}
}
</style>